<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>canvas</title>
  <style>
    canvas {
      border: 1px solid #000;
    }
  </style>
</head>

<body>

  <button id="btn1">画一个矩形</button>
  <button id="btn2">画一个矩形边框</button>
  <button id="btn3">清屏</button>
  <br><br>

  <canvas width="500" height="400" id="my-canvas">
    当前浏览器版本不支持，请升级浏览器
  </canvas>

  <script>
    const btn1 = document.getElementById("btn1");
    const btn2 = document.getElementById("btn2");
    const btn3 = document.getElementById("btn3");

    // 1. 获取到canvas画布
    var canvas = document.getElementById("my-canvas");
    // 得到画布的上下文
    var ctx = canvas.getContext("2d");

    // 矩形绘制
    btn1.onclick = function () {
      ctx.fillStyle = "green";
      ctx.fillRect(10, 100, 50, 50);
    }

    // 绘制矩形边框
    btn2.onclick = function () {
      ctx.strokeStyle = "blue";
      ctx.strokeRect(80, 100, 50, 50);
    }

    // 清屏
    btn3.onclick = function () {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    }

  </script>
</body>

</html>